"use client"

import { Button } from "@/components/ui/button"
import { useState, useEffect } from "react"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Calendar, Plus, ChevronLeft, ChevronRight, ClipboardCheck, AlertCircle } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Calendar as CalendarComponent } from "@/components/ui/calendar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { format } from "date-fns"
import { apiClient } from "@/lib/api"
import { transformToGroupedData } from "@/lib/data-utils"
import type { SampleFilters, SampleGroup, BackendPaginatedResponse, ApiResponse, Sample } from "@/types"

export default function QCSamplingPage() {
  const [groups, setGroups] = useState<SampleGroup[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedMixedGroups, setSelectedMixedGroups] = useState<string[]>([])
  const [lastSelectedIndex, setLastSelectedIndex] = useState<number | null>(null)
  const [isShiftPressed, setIsShiftPressed] = useState(false)

  // 筛选和分页状态
  const [searchTerm, setSearchTerm] = useState("")
  const [startDate, setStartDate] = useState<Date | undefined>(undefined)
  const [endDate, setEndDate] = useState<Date | undefined>(undefined)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [totalGroups, setTotalGroups] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [totalSamples, setTotalSamples] = useState(0)

  // 对话框状态
  const [showSamplingDialog, setShowSamplingDialog] = useState(false)

  // 统计数据
  const [stats, setStats] = useState({
    mixedOnly: 0,
    mixedGroups: 0,
    samplingGroups: 0,
  })

  // 监听Shift键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Shift") setIsShiftPressed(true)
    }
    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.key === "Shift") setIsShiftPressed(false)
    }

    window.addEventListener("keydown", handleKeyDown)
    window.addEventListener("keyup", handleKeyUp)
    return () => {
      window.removeEventListener("keydown", handleKeyDown)
      window.removeEventListener("keyup", handleKeyUp)
    }
  }, [])

  // 获取只有混合编号的样品数据
  const fetchSamples = async () => {
    setLoading(true)
    try {
      const filters: SampleFilters = {
        search: searchTerm,
        status: "mixed-only", // 只获取有混合编号但无抽检编号的样品
        startDate: startDate?.toISOString(),
        endDate: endDate?.toISOString(),
        page: currentPage,
        pageSize: pageSize,
      }

      const queryParams = new URLSearchParams()
      Object.entries(filters).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== "") {
          queryParams.append(key, value.toString())
        }
      })

      const result: ApiResponse<BackendPaginatedResponse<Sample>> = await apiClient.get(`/samples?${queryParams}`)

      if (result.success && result.data) {
        const backendData = result.data

        // 转换为前端分组格式
        const transformedData = transformToGroupedData(backendData, "mixed-only")

        setGroups(transformedData.groups)
        setTotalGroups(transformedData.total)
        setTotalPages(transformedData.totalPages)
        setTotalSamples(transformedData.totalSamples)
      }
    } catch (error) {
      console.error("获取样品数据失败:", error)
    } finally {
      setLoading(false)
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      // 注意：这里应该定义具体的StatsResponse类型，暂时使用any
      const result: ApiResponse<any> = await apiClient.get("/samples/stats")
      if (result.success && result.data) {
        setStats({
          mixedOnly: result.data.mixedOnly,
          mixedGroups: result.data.mixedGroups,
          samplingGroups: result.data.samplingGroups,
        })
      }
    } catch (error) {
      console.error("获取统计数据失败:", error)
    }
  }

  useEffect(() => {
    fetchSamples()
  }, [currentPage, pageSize, searchTerm, startDate, endDate])

  useEffect(() => {
    fetchStats()
  }, [])

  // 处理混合编号组选择
  const handleSelectMixedGroup = (mixedNumber: string, checked: boolean, index: number) => {
    if (isShiftPressed && lastSelectedIndex !== null) {
      const mixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
      const currentMixedIndex = mixedNumbers.indexOf(mixedNumber)
      const lastMixedIndex = lastSelectedIndex

      if (currentMixedIndex !== -1 && lastMixedIndex !== -1) {
        const start = Math.min(lastMixedIndex, currentMixedIndex)
        const end = Math.max(lastMixedIndex, currentMixedIndex)
        const rangeMixedNumbers = mixedNumbers.slice(start, end + 1)
        const newSelected = [...new Set([...selectedMixedGroups, ...rangeMixedNumbers])]
        setSelectedMixedGroups(newSelected)
      }
    } else {
      if (checked) {
        setSelectedMixedGroups([...selectedMixedGroups, mixedNumber])
      } else {
        setSelectedMixedGroups(selectedMixedGroups.filter((id) => id !== mixedNumber))
      }
      const mixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
      const currentIndex = mixedNumbers.indexOf(mixedNumber)
      setLastSelectedIndex(currentIndex)
    }
  }

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      const allMixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
      setSelectedMixedGroups(allMixedNumbers)
    } else {
      setSelectedMixedGroups([])
    }
  }

  // 生成抽检编号
  const generateSamplingNumbers = async () => {
    if (selectedMixedGroups.length === 0) {
      alert("请先选择要进行质控抽检的混样组")
      return
    }

    try {
      const result: ApiResponse<void> = await apiClient.post("/samples/generate-sampling", {
        mixedNumbers: selectedMixedGroups,
      })

      if (result.success) {
        alert(result.message)
        setSelectedMixedGroups([])
        setShowSamplingDialog(false)
        fetchSamples()
        fetchStats()
      } else {
        alert(result.message || "质控抽检处理失败")
      }
    } catch (error) {
      alert("网络错误，请稍后重试")
    }
  }

  const getMixedNumberColor = (mixedNumber: string) => {
    const colors = [
      "bg-blue-100 text-blue-800",
      "bg-green-100 text-green-800",
      "bg-purple-100 text-purple-800",
      "bg-orange-100 text-orange-800",
    ]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return colors[index]
  }

  const getMixedCellBorderStyle = (mixedNumber: string) => {
    const baseStyle = "border-l-4"
    const colors = ["border-blue-300", "border-green-300", "border-purple-300", "border-orange-300"]
    const index = Number.parseInt(mixedNumber.replace("MX", "")) % colors.length
    return `${baseStyle} ${colors[index]}`
  }

  const allMixedNumbers = groups.map((group) => group.mixedNumber!).filter(Boolean)
  const isAllSelected = allMixedNumbers.length > 0 && selectedMixedGroups.length === allMixedNumbers.length
  const isPartialSelected = selectedMixedGroups.length > 0 && selectedMixedGroups.length < allMixedNumbers.length

  return (
      <div className="p-6 space-y-6">
        {/* 页面标题 */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <ClipboardCheck className="h-7 w-7 text-green-600" />
              质控抽检处理
            </h1>
            <p className="text-muted-foreground">对已完成混样的样品组进行质控抽检编号分配</p>
          </div>
          <Dialog open={showSamplingDialog} onOpenChange={setShowSamplingDialog}>
            <DialogTrigger asChild>
              <Button disabled={selectedMixedGroups.length === 0} className="bg-green-600 hover:bg-green-700">
                <Plus className="w-4 h-4 mr-2" />
                分配抽检编号 ({selectedMixedGroups.length})
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>质控抽检编号分配</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    已选择 {selectedMixedGroups.length} 个混样组进行质控抽检，将生成 1 个抽检编号。
                    <br />
                    选中的混样编号：{selectedMixedGroups.join(", ")}
                  </AlertDescription>
                </Alert>
                <div className="bg-blue-50 p-3 rounded-lg text-sm">
                  <strong>质控抽检说明：</strong>
                  <ul className="mt-2 space-y-1 text-muted-foreground">
                    <li>• 抽检编号用于质量控制和追溯管理</li>
                    <li>• 一个抽检编号可以包含多个混样组</li>
                    <li>• 分配后将进入最终的处理完成状态</li>
                  </ul>
                </div>
                <div className="flex justify-end gap-2">
                  <Button variant="outline" onClick={() => setShowSamplingDialog(false)}>
                    取消
                  </Button>
                  <Button onClick={generateSamplingNumbers} className="bg-green-600 hover:bg-green-700">
                    确认分配
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>

        {/* 统计信息 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card className="border-l-4 border-yellow-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">待抽检样品数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-yellow-600">{stats.mixedOnly}</div>
              <div className="text-xs text-muted-foreground mt-1">已混样但未抽检的样品</div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-green-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">已选择组数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-green-600">{selectedMixedGroups.length}</div>
              <div className="text-xs text-muted-foreground mt-1">
                {selectedMixedGroups.length > 0 && "将生成 1 个抽检编号"}
              </div>
            </CardContent>
          </Card>
          <Card className="border-l-4 border-purple-400">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">当前页样品数</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-purple-600">{totalSamples}</div>
              <div className="text-xs text-muted-foreground mt-1">本页显示的样品数量</div>
            </CardContent>
          </Card>
        </div>

        {/* 搜索和筛选条件 */}
        <div className="flex gap-4 items-center flex-wrap">
          <Input
              placeholder="搜索样品编号、名称、操作人..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-64"
          />

          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" size="icon">
                <Calendar className="h-4 w-4" />
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="end">
              <div className="p-3 border-b">
                <div className="text-sm font-medium">混样处理时间范围</div>
              </div>
              <div className="p-3 flex flex-col gap-2">
                <div>
                  <div className="text-xs mb-1">开始日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={startDate}
                      onSelect={setStartDate}
                      className="border rounded-md"
                  />
                </div>
                <div>
                  <div className="text-xs mb-1">结束日期</div>
                  <CalendarComponent
                      mode="single"
                      selected={endDate}
                      onSelect={setEndDate}
                      className="border rounded-md"
                  />
                </div>
                <div className="flex justify-end">
                  <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        setStartDate(undefined)
                        setEndDate(undefined)
                      }}
                  >
                    重置
                  </Button>
                </div>
              </div>
            </PopoverContent>
          </Popover>

          <Select value={pageSize.toString()} onValueChange={(value) => setPageSize(Number(value))}>
            <SelectTrigger className="w-32">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="5">5组/页</SelectItem>
              <SelectItem value="10">10组/页</SelectItem>
              <SelectItem value="20">20组/页</SelectItem>
              <SelectItem value="50">50组/页</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* 样品表格 */}
        <Card>
          <CardContent className="p-0">
            {loading ? (
                <div className="flex items-center justify-center h-64">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
                </div>
            ) : totalSamples === 0 ? (
                <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
                  <ClipboardCheck className="h-12 w-12 mb-4" />
                  <p className="text-lg font-medium">暂无待抽检样品</p>
                  <p className="text-sm">所有混样组都已完成质控抽检处理</p>
                </div>
            ) : (
                <>
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-gray-100">
                        <TableHead className="w-12">
                          <Checkbox
                              checked={isAllSelected}
                              {...(isPartialSelected ? { indeterminate: true } : {})}
                              onCheckedChange={handleSelectAll}
                          />
                        </TableHead>
                        <TableHead>混样编号</TableHead>
                        <TableHead>样品编号</TableHead>
                        <TableHead>样品名称</TableHead>
                        <TableHead>样品类型</TableHead>
                        <TableHead>送检单位</TableHead>
                        <TableHead>混样操作人</TableHead>
                        <TableHead>混样时间</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {groups.map((group) => {
                        const mixedNumber = group.mixedNumber!
                        const isSelected = selectedMixedGroups.includes(mixedNumber)

                        return group.samples.map((sample, sampleIndex) => {
                          const showMixedCell = sampleIndex === 0
                          const showCheckbox = sampleIndex === 0

                          return (
                              <TableRow
                                  key={sample.id}
                                  className={isSelected ? "bg-green-50" : "bg-yellow-50 hover:bg-yellow-100"}
                              >
                                <TableCell>
                                  {showCheckbox && (
                                      <Checkbox
                                          checked={isSelected}
                                          onCheckedChange={(checked) =>
                                              handleSelectMixedGroup(mixedNumber, checked as boolean, sampleIndex)
                                          }
                                      />
                                  )}
                                </TableCell>
                                {showMixedCell && (
                                    <TableCell
                                        rowSpan={group.samples.length}
                                        className={`align-middle ${getMixedCellBorderStyle(mixedNumber)}`}
                                    >
                                      <Badge variant="secondary" className={getMixedNumberColor(mixedNumber)}>
                                        {mixedNumber}
                                      </Badge>
                                    </TableCell>
                                )}
                                <TableCell className="font-mono text-sm">{sample.sampleNumber}</TableCell>
                                <TableCell>{sample.sampleName}</TableCell>
                                <TableCell>{sample.sampleType}</TableCell>
                                <TableCell>{sample.testingUnit}</TableCell>
                                <TableCell>{sample.operator || "-"}</TableCell>
                                <TableCell>
                                  {sample.operationTime ? format(new Date(sample.operationTime), "yyyy-MM-dd HH:mm") : "-"}
                                </TableCell>
                              </TableRow>
                          )
                        })
                      })}
                    </TableBody>
                  </Table>

                  {/* 分页控件 */}
                  <div className="flex items-center justify-between px-6 py-4 border-t">
                    <div className="text-sm text-muted-foreground">
                      显示第 {(currentPage - 1) * pageSize + 1} - {Math.min(currentPage * pageSize, totalGroups)} 组，共{" "}
                      {totalGroups} 个混样组 ({totalSamples} 个样品)
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                          disabled={currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                        上一页
                      </Button>
                      <div className="flex items-center gap-1">
                        {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                          let pageNum
                          if (totalPages <= 5) {
                            pageNum = i + 1
                          } else if (currentPage <= 3) {
                            pageNum = i + 1
                          } else if (currentPage >= totalPages - 2) {
                            pageNum = totalPages - 4 + i
                          } else {
                            pageNum = currentPage - 2 + i
                          }

                          return (
                              <Button
                                  key={pageNum}
                                  variant={currentPage === pageNum ? "default" : "outline"}
                                  size="sm"
                                  onClick={() => setCurrentPage(pageNum)}
                                  className="w-8 h-8 p-0"
                              >
                                {pageNum}
                              </Button>
                          )
                        })}
                      </div>
                      <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
                          disabled={currentPage === totalPages}
                      >
                        下一页
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </>
            )}
          </CardContent>
        </Card>

        {/* 操作说明 */}
        <Card>
          <CardContent className="p-4">
            <div className="text-sm space-y-2">
              <div>
                <strong>质控抽检处理说明：</strong>
              </div>
              <ul className="list-disc list-inside space-y-1 text-muted-foreground">
                <li>选择需要进行质控抽检的混样组，可以使用Shift键进行范围选择</li>
                <li>每个混样组包含多个已完成混样处理的样品</li>
                <li>点击"分配抽检编号"按钮，系统将为选中的所有混样组生成统一的抽检编号（SP001、SP002...）</li>
                <li>抽检编号用于质量控制和样品追溯管理</li>
                <li>完成抽检编号分配后，样品将进入最终的处理完成状态</li>
              </ul>
            </div>
          </CardContent>
        </Card>
      </div>
  )
}
